package com.campus.food.service.impl;

import com.campus.food.mapper.UserMapper;
import com.campus.food.model.entity.User;
import com.campus.food.model.dto.LoginDTO;
import com.campus.food.model.dto.RegisterDTO;
import com.campus.food.service.UserService;
import com.campus.food.util.JwtUtil;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户服务实现类
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;

    public static void main(String[] args) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(passwordEncoder.encode("123456"));
        System.out.println(passwordEncoder.matches("123456", "$2a$10$fZLUiz.iItBJ5RA9RU6gxO54jdbEswkrdXoGolbHIKun3Ewa4iuqm"));
    }
    
    @Override
    public User register(RegisterDTO registerDTO) {
        // 验证用户名是否已存在
        if (userMapper.existsByUsername(registerDTO.getUsername())) {
            throw BusinessException.badRequest("用户名已存在");
        }
        
        // 验证手机号是否已存在
        if (StringUtils.hasText(registerDTO.getPhone()) && userMapper.existsByPhone(registerDTO.getPhone())) {
            throw BusinessException.badRequest("手机号已被注册");
        }
        
        // 验证邮箱是否已存在
        if (StringUtils.hasText(registerDTO.getEmail()) && userMapper.existsByEmail(registerDTO.getEmail())) {
            throw BusinessException.badRequest("邮箱已被注册");
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setRealName(registerDTO.getRealName());
        user.setPhone(registerDTO.getPhone());
        user.setEmail(registerDTO.getEmail());
        user.setRole(registerDTO.getRole() != null ? registerDTO.getRole() : 1); // 默认为学生用户
        user.setStatus(1); // 默认启用状态
        
        // 保存用户
        int result = userMapper.insert(user);
        if (result <= 0) {
            throw BusinessException.error("注册失败");
        }
        
        return user;
    }
    
    @Override
    public String login(LoginDTO loginDTO) {
        // 根据用户名查询用户
        User user = userMapper.selectByUsername(loginDTO.getUsername());
        if (user == null) {
            throw BusinessException.badRequest("用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() == 0) {
            throw BusinessException.forbidden("账号已被禁用");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw BusinessException.badRequest("用户名或密码错误");
        }
        
        // 更新最后登录时间
        userMapper.updateLastLoginTime(user.getId(), LocalDateTime.now());
        
        // 生成JWT令牌
        return jwtUtil.generateToken(user.getId(), user.getUsername(), user.getRole());
    }
    
    @Override
    @Transactional(readOnly = true)
    public User getUserById(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw BusinessException.notFound("用户不存在");
        }
        return user;
    }
    
    @Override
    @Transactional(readOnly = true)
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }
    
    @Override
    public boolean updateUser(User user) {
        if (user.getId() == null) {
            throw BusinessException.badRequest("用户ID不能为空");
        }
        
        // 检查用户是否存在
        User existingUser = userMapper.selectById(user.getId());
        if (existingUser == null) {
            throw BusinessException.notFound("用户不存在");
        }
        
        // 如果更新用户名，检查是否重复
        if (StringUtils.hasText(user.getUsername()) && 
            !user.getUsername().equals(existingUser.getUsername()) &&
            userMapper.existsByUsername(user.getUsername())) {
            throw BusinessException.badRequest("用户名已存在");
        }
        
        // 如果更新手机号，检查是否重复
        if (StringUtils.hasText(user.getPhone()) && 
            !user.getPhone().equals(existingUser.getPhone()) &&
            userMapper.existsByPhone(user.getPhone())) {
            throw BusinessException.badRequest("手机号已被注册");
        }
        
        // 如果更新邮箱，检查是否重复
        if (StringUtils.hasText(user.getEmail()) && 
            !user.getEmail().equals(existingUser.getEmail()) &&
            userMapper.existsByEmail(user.getEmail())) {
            throw BusinessException.badRequest("邮箱已被注册");
        }
        
        // 如果更新密码，进行加密
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        
        return userMapper.updateById(user) > 0;
    }
    
    @Override
    public boolean updateUserStatus(Long id, Integer status) {
        if (id == null) {
            throw BusinessException.badRequest("用户ID不能为空");
        }
        
        // 检查用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            throw BusinessException.notFound("用户不存在");
        }
        
        return userMapper.updateStatus(id, status) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<User> getUserList(int page, int size, String username, String realName, Integer role, Integer status) {
        int offset = (page - 1) * size;
        return userMapper.selectPage(offset, size, username, realName, role, status);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getUserCount(String username, String realName, Integer role, Integer status) {
        return userMapper.selectCount(username, realName, role, status);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<User> getUsersByRole(Integer role) {
        return userMapper.selectByRole(role);
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean existsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean existsByPhone(String phone) {
        return userMapper.existsByPhone(phone);
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean existsByEmail(String email) {
        return userMapper.existsByEmail(email);
    }
    
    @Override
    public boolean deleteUser(Long id) {
        if (id == null) {
            throw BusinessException.badRequest("用户ID不能为空");
        }
        
        // 检查用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            throw BusinessException.notFound("用户不存在");
        }
        
        return userMapper.deleteById(id) > 0;
    }
    
    @Override
    public boolean updateLastLoginTime(Long id) {
        if (id == null) {
            throw BusinessException.badRequest("用户ID不能为空");
        }
        
        return userMapper.updateLastLoginTime(id, LocalDateTime.now()) > 0;
    }
    
    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        if (userId == null) {
            throw BusinessException.badRequest("用户ID不能为空");
        }
        
        // 校验参数
        if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword)) {
            throw BusinessException.badRequest("密码不能为空");
        }
        
        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw BusinessException.notFound("用户不存在");
        }
        
        // 验证原密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return false; // 原密码不正确
        }
        
        // 加密新密码
        String encodedPassword = passwordEncoder.encode(newPassword);
        
        // 更新密码
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setPassword(encodedPassword);
        
        return userMapper.updateById(updateUser) > 0;
    }
} 